import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:largefriends/config/lf_route.dart';
import 'package:largefriends/entity/entities/lf_user_entity.dart';
import 'package:largefriends/service/manager/lf_user_cache_manager.dart';
import 'package:largefriends/pages/lf_tab_contact/lf_contact_sub_logic.dart';
import 'package:largefriends/service/lf_auth_service.dart';

import '../../events/user_relation_event.dart';
import '../../service/manager/lf_event_helper.dart';
import '../../net/error_handle.dart';
import '../../net/lf_api_url.dart';
import '../../net/lf_api_util.dart';
import '../../net/lf_dio_util.dart';
import '../../utils/lf_dialog_utils.dart';
import '../lf_base_controller.dart';
import '../lf_report/lf_report_logic.dart';

toProfilePage(
    {required String uid, LfUserEntity? userEntity, ContactType? type}) {
  LfAuthService authService = Get.find();
  if (authService.currentAccount!.userId == uid) {
    Get.offNamedUntil(
        LFRoute.pathEditProfile, ModalRoute.withName(LFRoute.pathHome),
        arguments: {'isFromProfile': true});
    return;
  }
  if (Get.isRegistered<LfProfileLogic>(tag: uid)) {
    ///如果已经打开过相同的页面,可以直接返回那个页面去
    Get.until((route) =>
        route.settings.name == LFRoute.pathProfileDetail &&
        ((route.settings.arguments as Map)['uid'] == uid));
    return;
  }
  Get.toNamed(LFRoute.pathProfileDetail,
      arguments: {'uid': uid, 'userEntity': userEntity, 'contactType': type});
}

class LfProfileLogic extends GetxController {
  late String uid;
  LfUserEntity? userEntity;
  int hiddenCode = 0;
  LoadingState state = LoadingState.init;
  StreamSubscription? relationSubscription;
  @override
  void onInit() {
    uid = Get.arguments['uid'];
    userEntity = Get.arguments['userEntity'];
    var cache = LfUserCacheManager().getCacheUser(
      key: uid,
    );
    if (cache != null) {
      userEntity = LfUserCacheManager().getCacheUser(
        key: uid,
      );

      ///因为这里的信息是从接口获取的,更加完整一些
    }
    if (userEntity == null) {
      state = LoadingState.loading;
    } else {
      if (userEntity!.isHiddenForMe() ||
          !userEntity!.isEnable() ||
          userEntity!.isBlockMe()) {
        hiddenCode = 10001;
      }
      state = LoadingState.success;
    }
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    _getUserInfo();
    relationSubscription =
        LfEventHelper().getEvent().on<UserRelationEvent>().listen((event) {
      if (event.uid != uid) {
        return;
      }
      if (event.type == UserRelationType.block) {
        Get.back();
      } else if (event.type == UserRelationType.like) {
        userEntity?.liked = 1;
        if (userEntity != null) {
          update();
        }
      } else if (event.type == UserRelationType.unlike) {
        userEntity?.liked = 0;
        if (userEntity != null) {
          update();
        }
      } else if (event.type == UserRelationType.wink) {
        userEntity?.winked = 1;
        if (userEntity != null) {
          update();
        }
      } else if (event.type == UserRelationType.requestPrivate) {
        userEntity?.privateAlbumStatus = 2;
        if (userEntity != null) {
          update();
        }
      } else if (event.type == UserRelationType.requestAccept) {
        userEntity?.canAccessMyPrivate = 1;
        if (userEntity != null) {
          update();
        }
      }
    });
  }

  @override
  void onClose() {
    relationSubscription?.cancel();
    super.onClose();
  }

  _getUserInfo() {
    LfDio().get<LfUserEntity>(url: apiProfile, params: {
      'profId': uid,
      'isViewProfile': 1,
    }).then((value) {
      userEntity = value;
      LfUserCacheManager().setCacheUser(key: uid, user: userEntity);
      state = LoadingState.success;
      update();
    }, onError: (error) {
      state = LoadingState.failed;
      if (error is NetError) {
        if (error.code == 30001024) {
          //This profile is hidden. Please try again later
          hiddenCode = error.code;
          LfUserCacheManager().setCacheUser(key: uid, user: null);
        } else if (error.code == 30001032) {
          //You have blocked the user.
          hiddenCode = error.code;
          LfUserCacheManager().setCacheUser(key: uid, user: null);
        } else if (error.code == 30001033) {
          //The user has blocked you.
          hiddenCode = error.code;
          LfUserCacheManager().setCacheUser(key: uid, user: null);
        } else if (error.code == 30001035) {
          //This user is unavailable at this time.
          hiddenCode = error.code;
          LfUserCacheManager().setCacheUser(key: uid, user: null);
        } else if (userEntity == null) {
          showSnackBar(error.msg);
        }
      }
      update();
    });
  }

  void report() {
    toReportPage(userId: uid);
  }

  void block() {
    blockUser(uid: uid);
  }
}
